
package org.soekrat.engine.pitbul.parser;

import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;

import javax.swing.JFrame;

import org.soekrat.engine.forest.Forest;
import org.soekrat.engine.forest.Tree;
import org.soekrat.engine.util.Util;

public class ParseTree 
{
  public static Tree parse(String[] startTokens, String[] endTokens, 
    Iterable<String> tokens) throws IOException
  {
    if (startTokens==null)
    {
      throw new NullPointerException("startTokens");
    }
    
    // TODO
    
    Tree retVal=new Tree("root");
    
    Tree parent=retVal;
    
    for (String token : tokens)
    {
      if (Util.contains(startTokens, token))
      {
        parent=parent.createChild(token);
      }
      else if (Util.contains(endTokens, token))
      {
        Tree p=parent.getParent();
        if (p==null)
        {
          throw new IOException("unexpected end, start token not matched");
        }        
        parent=p;
        parent.createChild(token);
      }
      else
      {
        parent.createChild(token);  
      }
    }
    
    return retVal;
  }
  
  public static void main(String[] args) 
  {
    try
    {
      File f=new File("./documents/all.pit");
      
      
      //String s="{a 123 45 { {\"arne is { rat\" } yup}6789 10}";
      
      Tokenizer tokens=new Tokenizer();
      
      tokens.setTokenChars("{}");
      tokens.setIgnoreChars(";");
      
      tokens.parse(f);
      Tree t=parse(new String[]{ "{" }, new String[]{ "}" }, tokens);
      t.printHierarchy((String[])null);
      
      JFrame frame=new JFrame();
      frame.setLayout(new BorderLayout());
      
      Forest forest=new Forest();
      forest.addTree(t);
      SimpleForestTreePanel sftp=new SimpleForestTreePanel(forest);
      frame.add(sftp, BorderLayout.CENTER);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(300, 500);
      
      frame.setVisible(true);
      
      TreeFormParser tfp=new TreeFormParser(t);
      
     
    }
    catch (IOException iox)
    {
      iox.printStackTrace();
    }
  }

}
